package com.roc.producer.messageType;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.util.List;

public class OrderMsgProducer {
    public static void main(String[] args) throws Exception {
        // 实例化生产者，指定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("roc_producer_group");
        // 设置 NameServer 地址
        producer.setNamesrvAddr("127.0.0.1:9876");
        // 启动生产者
        producer.start();

        String[] tags = new String[]{"TagA", "TagB", "TagC", "TagD", "TagE"};
        String[] orderStatus = new String[]{"step-1-创建", "step-2-付款", "step-3-完成"};

        // 模拟发送5个订单的消息，每个订单有3个步骤（创建、付款、完成）
        for (int i = 0; i < 5; i++) {
            int orderId = i;
            for (int j = 0; j < 3; j++) {
                // 创建消息，指定Topic、Tag和消息体
                Message msg = new Message("TOPIC_ORDER", tags[j % tags.length],
                        "KEY" + i,
                        ("订单号：" + orderId + ", 步骤： " + orderStatus[j]).getBytes());

                // 发送顺序消息，使用订单ID作为选择队列的key，确保同一订单的消息发送到同一个队列
                SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
                    @Override
                    public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                        Integer id = (Integer) arg;
                        int index = id % mqs.size();
                        return mqs.get(index);
                    }
                }, orderId);

                System.out.printf("消息内容: %s%n", new String(msg.getBody()));
                System.out.printf("%s%n", sendResult);
                System.out.println("\n");
            }
        }

        // 关闭生产者
        producer.shutdown();
    }
}